<?php
class UsersController extends AppController
{


    public function beforeFilter()
    {
        parent::beforeFilter();
        $this->Auth->allow('add');
    }

    public function isAuthorized($user)
    {
        // Admin can access every action
        //debug(isset($user['role']));
        // debug($user['role']);
        // if (isset($user['role']) && $user['role'] !== 'admin' && ($this->action !== 'login' && $this->action !== 'logout')) {
        //  return false;
        //}

        return true;
    }

    public function login()
    {
//debug($this->Session->id());
//debug($this->Session->reNew());
//debug($this->Session->write('App.testString', 'test'));
//debug($this->Session->read('App.testString'));
        if ($this->request->is('post')) { //si es un post de un formulario

            if ($this->Auth->login()) {
                $this->redirect($this->Auth->redirect());

            } else {
                $this->Session->setFlash('Usuario y contraseña inválidos','errorMessage',array(),'usuario');
            }
        }


    }

    function edit($id = null)
    {
        $this->User->id = $id;
        if ($this->request->is('get')) {
            $this->request->data = $this->User->read();
        } else {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash('El usuario ha sido actualizado.');
                $this->redirect(array('action' => 'index'));
            }
        }
    }

    function delete($id)
    {
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        if ($this->User->delete($id)) {
            $this->Session->setFlash('El usuario ha sido borrado.');
            $this->redirect($this->referer());
        }
    }

    public function index()
    {
        $this->User->recursive = 0;
        $this->set('users', $this->paginate());
    }

    public function view($id)
    {
        $this->User->id = $id;
        $this->set('user', $this->User->read());

    }


    public function add()
    {
        //debug($this->User);
        //debug($this->request);
        if ($this->request->is('post')) { //si es un post de un formulario
            $this->User->create();
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash('El usuario ha sido almacenado','infoMessage',array(),'usuario');
                //$this->redirect(array('controller' => 'pages',  'action' => 'display', 'home'));
            } else {
                $this->Session->setFlash('El usuario no ha podido ser guardado. Inténtelo de nuevo más tarde');
            }
        }
        $this->User->recursive = 0;
        $this->set('users', $this->paginate());
    }

    public function logout()
    {
        $this->redirect($this->Auth->logout());
    }
}
